import { Card, Button, Modal, message } from 'antd'
import Moment from 'react-moment'
import StatusTag from '@/components/StatusTag'
import { useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { $api } from '@/http/api'

const CardButton = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const cancelOrder = (id) => {
    $api.user.cancelOrder({
      id: id
    }).then((res) => {
      if (res.code === 200) {
        message.success("Cancel order successfully!")
        props.refresh()
        handleCancel()
      }
    })
  }

  const navigate = useNavigate();

  const detail = () => {
    navigate(`/order/${props.id}`);
  }

  return (
    <>
      <StatusTag status={props.status} />
      <Button type="link" onClick={detail}>Detail</Button>
      {props.status < 4 ?
        <>
          <Button type="primary" onClick={showModal}>Cancel</Button>
          <Modal title="Cancel the order" visible={isModalVisible} onOk={e => cancelOrder(props.id)} onCancel={handleCancel}>
            <div className='text-item'>⏰ <Moment format="YYYY-MM-DD HH:mm">{props.orderTime}</Moment> 💷 {props.totalPrice}</div>
            {props.food.map((item, index) => {
              return (
                <div key={index} className='text-item'>{item.name} * {item.number}</div>
              )
            })}
          </Modal>
        </>
        : null}
    </>
  )
}

const OrderCard = (props) => {
  let distance = null
  if (props.status == 3) {
    $api.order.getOrderDistance({
      id: props.id
    }).then(res => {
      if (res.code === 200) {
        distance = res.data.distance_km
      }
    })
  }

  return (
    <Card size="small" title={props.restaurantName} extra={<CardButton {...props} />}>
      <div className='text-item'>⏰ <Moment format="YYYY-MM-DD HH:mm">{props.orderTime}</Moment> 💷 {props.totalPrice}</div>
      {distance !== null ? <div className='text-item'>🛵 {distance} km</div> : null}
      {props.food.map((item, index) => {
        return (
          <div key={index} className='text-item'>{item.name} * {item.number}</div>
        )
      })}
    </Card>
  )
}

export default OrderCard